<?php
namespace app\api\controller;
require_once env('root_path')."vendor/tp_wechat/Wechat.php";
use vendor\tp_wechat\Wechat as WechatObj;
use think\Controller;
use services\OpensslService;
use think\Request;
use think\Db;
class Login 
{
    protected $weconfig = [];
    protected $Obj;
    function __construct()
    {
        $this->weconfig = ['appid'=>config('fwhappid'),'appsecret'=>config('fwhappsecret')];
        $this->WechatObj = new WechatObj($this->weconfig);
        $this->Obj = $this->WechatObj->oauth($this->weconfig);
    }
    //小程序用户三方登陆
    public function userLogin()
    {
        if (request()->isPost()) {
            $param = request()->param();
            $login = Controller('Login', 'logic');
            $res = $login->thirdByUserLogin($param);
            write_log(json_encode($res));
            return json($res)->code(200)->header(['Content-Type' => 'application/json']);
        }
    }
    /**
     * @param $input
     * @return mixed  退出
     */
    public function user_logout(){
        $data = array();
        $data['token_user_id'] = isset($input['token_user_id']) ? $input['token_user_id'] : 0;
        if (empty($data['token_user_id'])) {
            $this->return_data['Msg'] = '参数错误';
            return $this->print_result($this->return_data);
        }
        $login = Controller('Login', 'logic');
        $res = $login->userLogout($data);
        return $this->print_result($res);
    }
    /****刷新token*****/
    public function refreshToken($input){
        $data = array();
        $data['user_id'] = isset($input['user_id']) ? $input['user_id'] : 0;
//        $data['token_user_type'] = isset($input['token_user_type']) ? $input['token_user_type'] : 0;
        if (empty($data['user_id'])) {
            $this->res_data['Msg'] = '参数错误';
            return $this->print_result($this->res_data);
        }
        //$ip = request()->ip();
        $expiresAt = time() + 7200;
        $token_data = [
            'expires_in' => 7200,
         //   'ip' => $ip,
            'uid' => $data['user_id'],
            //'user_type' => $data['token_user_type'],
            'created_at' => time(),
            'expiresAt' => $expiresAt
        ];
        $token = $this->createUserToken($token_data);
        $update = Db::name('user')->where('id',$data['user_id'])->update(['user_token'=>$token]);
        $this->res_data['Code'] = 0;
        $this->res_data['Data'] = ['token'=>$token];
        return $this->print_result($this->res_data);
    }
    /****创建令牌*****/
    public function createUserToken($data){
        if(!is_array($data)) return false;
        $map=array();
        $expiresAt = $data["created_at"] + $data['expires_in'];
        $map["user_id"]=trim($data["uid"]);//自己编号或上级编号
        $map["created_at"]=$data["created_at"];
        $map["expires_at"]=$expiresAt;
        $map["ip"] = ip2long($data["ip"]);
        $OpensslService = new OpensslService();
        $token=$OpensslService->aes_encrypt(json_encode($map));
        return $token;
    }


    public function getUserByOpenid($input)
    {
        $data['openid'] = isset($input['openid']) ? $input['openid'] : 0;
        if (!$data['openid']) {
            $this->res_data['Msg'] = '参数错误';
            return json($this->res_data)->code(200)->header(['Content-Type' => 'application/json']);
        }
        $user = Db::name('user')->field('id as user_id')->where(['openid'=>$data['openid']])->find();
        if (!$user) {
            $this->res_data['Msg'] = '参数错误';
            $this->res_data['Data'] = [];
            return json($this->res_data)->code(200)->header(['Content-Type' => 'application/json']);
        }
        $userLogin = Controller('User', 'logic');
        $res = $userLogin->userInfo($user);
        if ($res['Code']!=0) {
            $this->res_data['Msg'] = '登录失败';
            return json($this->res_data)->code(200)->header(['Content-Type' => 'application/json']);
        }
        $login = Controller('login', 'logic');
        $res2 = $login->updateToken($user);
        $res['token'] = $res2['Data'];
        return json($res)->code(200)->header(['Content-Type' => 'application/json']);
    }


    public function getFwhOpenid($input)
    {
        $openid = isset($input['openid']) ? $input['openid'] : '';
        $sid = isset($input['sid']) ? $input['sid'] : '';
        write_log($openid);
        if (!$openid) {
            return json(['Code'=>1,'Msg'=>'缺少参数'])->code(200)->header(['Content-Type' => 'application/json']);
        }
        $state = base64_encode($openid);
        $callback = config('http_domain').'/api/authnotify?sid='.$sid;
        $res = $this->Obj->getOauthRedirect($callback,$state,'snsapi_base');
        write_log($res);
        header('Location:'.$res);exit;
    }


    public function authnotify($input)
    {
        $code = isset($input['code']) ? $input['code'] : '';
        $state = isset($input['state']) ? $input['state'] : '';
        write_log($state);
        if (!$code || !$state) {
            return json([
                'Msg' => '授权失败',
                'Data' => [],
            ])->code(200)->header(['Content-Type' => 'application/json']);
        }
        // openid
        $openid = '';
        if ($state!='state') {
            $openid = base64_decode($state);
        }
        $return = $this->Obj->getOauthAccessToken($code);
        if (!$return) {
            return json([
                'Msg' => '授权失败',
                'Data' => [],
            ])->code(200)->header(['Content-Type' => 'application/json']);
        }
        $access_token = $return['access_token'];
        $fwhopenid = $return['openid'];
        // 绑定服务号openid
        $is_update = Db::name('user')->where(['openid'=>$openid])->update(['fwhopenid'=>$fwhopenid,'update_time'=>time()]);
        if (!$is_update) {
            return json([
                'Msg' => '授权失败',
                'Data' => [],
            ])->code(200)->header(['Content-Type' => 'application/json']);
        }
        // return json([
        //     'Msg' => '授权成功',
        //     'Code' => 0,
        // ])->code(200)->header(['Content-Type' => 'application/json']);
    }


    // 获取小程序openid
    public function getOpenidByCode($input)
    {
        $code = isset($input['code']) ? $input['code'] : '';
        if (!$code) {
            return json([
                'Msg' => '授权失败',
                'Data' => [],
            ])->code(200)->header(['Content-Type' => 'application/json']);
        }
        $xcxconfig = ['appid'=>config('appid'),'appsecret'=>config('appsecret')];
        $WechatObj = new WechatObj($xcxconfig);
        $Obj = $WechatObj->oauth($xcxconfig);
        $return = $Obj->getXcxOauthOpenid($code);
        write_log(json_encode($return));
        if (!$return) {
            return json([
                'Msg' => '授权失败',
                'Data' => [],
            ])->code(200)->header(['Content-Type' => 'application/json']);
        }
        $user = Db::name('user')->field('id as user_id')->where(['openid'=>$return['openid']])->find();
        if ($user) {
            $userLogin = Controller('User', 'logic');
            $res = $userLogin->userInfo($user);
            if ($res['Code']!=0) {
                $this->res_data['Msg'] = '登录失败';
                return json($this->res_data)->code(200)->header(['Content-Type' => 'application/json']);
            }
            $login = Controller('login', 'logic');
            $res2 = $login->updateToken($user);
            $res['token'] = $res2['Data'];
        }
        // $res['session_key'] = $return['session_key'];
        $res['openid'] = $return['openid'];
        cache($return['openid'], $return['session_key'], 3600);
        return json($res)->code(200)->header(['Content-Type' => 'application/json']);
    }
}
